package com.axend.lib_base.view.input;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.annotation.Nullable;

import com.axend.lib_base.R;
import com.axend.lib_base.databinding.BaseViewCustomInputBinding;
import com.axend.lib_base.utils.SoftKeyBoardUtils;
import com.axend.lib_base.view.spinner.OnSpinnerItemSelectedListener;

import java.util.Arrays;

/**
 * @author admins
 * @description 自定义输入控件
 * @time 2024/6/4 17:50
 */
public class CustomInputView extends LinearLayout {
    public static final int SHOW_TYPE_INPUT = 0;

    private boolean focusStatus; //光标软件盘控制
    private int titleColor;//标题文字颜色
    private String title;   //标题内容
    private float titleSize; //标题尺寸
    private String hint;//提示
    private boolean showInput;//显示输入框
    private boolean showSpinner;//显示下拉框
    private boolean showSwitch;//显示开关
    private boolean showText; //显示文本
    private float inputMarginLeft;
    private CharSequence[] spinnerEntries = new CharSequence[]{""};
    private int InputType;
    private boolean mShowPopup;
    private int maxLength;
    Context context;

    private BaseViewCustomInputBinding binding;


    public CustomInputView(Context context, String title, String hint, int leftMargin, boolean showText, boolean focusStatus) {
        super(context);
        binding = BaseViewCustomInputBinding.inflate(LayoutInflater.from(getContext()), this, true);
        this.context = context;
        this.hint = hint;
        this.inputMarginLeft = leftMargin;
        this.showText = showText;
        this.focusStatus = focusStatus;
        this.titleColor = R.color.black;
        this.titleSize = 34;
        this.title = title;
        setUpView();
    }


    public CustomInputView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        binding = BaseViewCustomInputBinding.inflate(LayoutInflater.from(getContext()), this, true);
        this.context = context;
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CustomInputView, 0, 0);
        try {
            title = ta.getString(R.styleable.CustomInputView_title);
            titleColor = ta.getResourceId(R.styleable.CustomInputView_titleColor, R.color.black);
            titleSize = ta.getDimension(R.styleable.CustomInputView_titleSize, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 34, getResources().getDisplayMetrics()));
            hint = ta.getString(R.styleable.CustomInputView_hint);
            focusStatus = ta.getBoolean(R.styleable.CustomInputView_focusStatus, true);
            showText = ta.getBoolean(R.styleable.CustomInputView_showText, false);
            showInput = ta.getBoolean(R.styleable.CustomInputView_showInput, false);
            showSpinner = ta.getBoolean(R.styleable.CustomInputView_showSpinner, false);
            showSwitch=ta.getBoolean(R.styleable.CustomInputView_showSwitch,false);
            inputMarginLeft = ta.getDimension(R.styleable.CustomInputView_inuputMarginLeft, 0);
            spinnerEntries = ta.getTextArray(R.styleable.CustomInputView_spinnerEntries);
            InputType = ta.getInt(R.styleable.CustomInputView_customInputType, 0x00000001);
            mShowPopup = ta.getBoolean(R.styleable.CustomInputView_showPopup, true);
            maxLength = ta.getInt(R.styleable.CustomInputView_editMaxLength, 10);
            setUpView();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ta.recycle();
        }

    }

    private void setUpView() {
        if (showInput) {
            updateVisibility(true, false, false,false);
        } else if (showSpinner) {
            updateVisibility(false, true, false,false);
        } else if (showSwitch){
            updateVisibility(false, false, false,true);
        }else {
            updateVisibility(false, false, true,false);
        }
        binding.etInput.setHint(hint);
        binding.niceSpinner.setHint(hint);
        binding.niceSpinner.setShowPopup(mShowPopup);
        binding.etInput.setInputType(InputType);
        binding.etInput.setMaxLines(1);
        binding.etInput.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)});

        if (inputMarginLeft != 0) {
            RelativeLayout.LayoutParams input = (RelativeLayout.LayoutParams) binding.llInputView.getLayoutParams();
            input.leftMargin = (int) inputMarginLeft;
            binding.llInputView.setLayoutParams(input);
        }
        binding.tvTitle.setText(title);
        binding.tvTitle.setTextColor(getResources().getColor(titleColor));
        binding.tvTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, titleSize);

        if (spinnerEntries != null) {
            binding.niceSpinner.attachDataSource(Arrays.asList(spinnerEntries));
        }

        setFocusStatus(focusStatus);
        //软键盘显示/隐藏监听
        SoftKeyBoardUtils softKeyBoardUtils = new SoftKeyBoardUtils((Activity) context);
        softKeyBoardUtils.setListener(new SoftKeyBoardUtils.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {

            }

            @Override
            public void keyBoardHide(int height) {

            }
        });
    }

    public void updateVisibility(boolean showInput, boolean showSpinner, boolean showText,boolean showSwitch) {
        binding.etInput.setVisibility(showInput ? VISIBLE : GONE);
        binding.niceSpinner.setVisibility(showSpinner ? VISIBLE : GONE);
        binding.tvContent.setVisibility(showText ? VISIBLE : GONE);
        binding.commonSwitch.setVisibility(showSwitch?VISIBLE:GONE);
    }


    public void setTvTitle(String tvTitle) {
        binding.tvTitle.setText(tvTitle);
    }

    public void setTvTitle(String tvTitle, int insertColor, String insertStr, int insertIndex) {
        SpannableStringBuilder ssb = new SpannableStringBuilder(tvTitle);
        int positionToInsert = insertIndex; // 想要插入的位置
        ssb.insert(positionToInsert, insertStr);
        ssb.setSpan(new ForegroundColorSpan(insertColor), positionToInsert, positionToInsert + insertStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        binding.tvTitle.setText(ssb);
    }


    public void setFocusStatus(boolean isFocus) {
        binding.etInput.setFocusable(isFocus);
        binding.etInput.setFocusableInTouchMode(isFocus);
        binding.etInput.setCursorVisible(isFocus);
    }

    public void setEditType(int type) {
        binding.etInput.setInputType(type);
    }


    public void setContentText(String text) {
        binding.tvContent.setText(text);
    }

    /**
     * spinner点击事件
     *
     * @param listener
     */
    public void setOnSpinnerClickListener(OnClickListener listener) {
        binding.niceSpinner.setOnClickListener(listener);
    }

    public void setEditTextRedTipsBackground(boolean mShow) {
        binding.etInput.setBackgroundResource(mShow ? R.drawable.selector_red_three : R.drawable.selector_gray_three);

    }

    public void setOnSpinnerItemSelectedListener(OnSpinnerItemSelectedListener onSpinnerItemSelectedListener){
        binding.niceSpinner.setOnSpinnerItemSelectedListener(onSpinnerItemSelectedListener);
    }

    public void setOnEditChange(final OnTextChange change) {
        binding.etInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!editable.toString().isEmpty()) {
                    change.changeAfter(editable.toString());
                } else {
                    change.changeAfter("0");
                }
            }
        });
    }


    public void setDynamicChange(final OnDynamicTextChange change, final String tag) {
        binding.etInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!editable.toString().isEmpty()) {
                    change.changeAfter(editable.toString(), tag);
                } else {
                    change.changeAfter("0", tag);
                }

            }
        });
    }

    /**
     * 获取switch状态
     * @return
     */
    public boolean getSwitchStatus(){
        return binding.commonSwitch.isChecked();
    }

    public void setSwitchStatus(boolean status){
        binding.commonSwitch.setChecked(status);
    }


    /**
     * @author：Easonchen
     * @description 获取输入框宽度
     */

    public int getEditWidth() {
        return binding.llInputView.getWidth();
    }

    /**
     * @author：Easonchen
     * @description 获取当前控件
     * @params
     */

    public String getEditText() {
        return binding.etInput.getText().toString();
    }


    public String getSpinnerText() {
        return (String) binding.niceSpinner.getSelectedItem();
    }

    public String getSpinnerContent() {
        return binding.niceSpinner.getText().toString();
    }

    public void setSpinnerText(String text) {
        binding.niceSpinner.setText(text);
    }

    public int getSpinnerPosition() {
        return binding.niceSpinner.getSelectedIndex();
    }

    public void setSpinnerPosition(int position) {
        binding.niceSpinner.setSelectedIndex(position);
    }


    public float getEditTextOfNumber() {
        String InputStr = binding.etInput.getText().toString().trim();
        return InputStr.equals("") ? 0 : Float.valueOf(InputStr);
    }

    /**
     * @author：Easonchen
     * @description 设置编辑内容
     * @params 内容
     */

    public void setEditText(String text) {
        binding.etInput.setText(text);
    }


    /**
     * @author：Easonchen
     * @description 清空内容
     * @params
     */

    public void viewClear() {
        binding.etInput.setText("");
    }


    public void setFilters(InputFilter[] filters) {
        binding.etInput.setFilters(filters);
    }


    public interface OnTextChange {
        /**
         * edittext监听
         *
         * @param value
         */
        void changeAfter(String value);
    }


    public interface OnDynamicTextChange {
        /**
         * edittext监听(带标签)
         *
         * @param value
         * @param tag
         */
        void changeAfter(String value, String tag);
    }
}
